import { createRouter, createWebHistory } from 'vue-router'
import AuthView from '../views/AuthView.vue'
import HomeView from '../views/HomeView.vue'
import { useAuthStore } from '@/stores/auth' // 引入 Auth Store
import ChatView from '../views/ChatView.vue'
import ChatRoomView from '../views/ChatRoomView.vue'
import MineView from '../views/MineView.vue'
import PostDetailView from '../views/PostDetailView.vue'
import PostCreateView from '../views/PostCreateView.vue'
import UserProfileView from '../views/UserProfileView.vue'
import FaceVerifyView from '../views/FaceVerifyView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/auth',
    },
    {
      path: '/auth',
      name: 'auth',
      component: AuthView,
      // 添加 meta 信息，标记这个页面不需要登录
      meta: { requiresAuth: false },
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      // 添加 meta 信息，标记这个页面需要登录
      meta: { requiresAuth: true },
    },
    {
      path: '/chat',
      name: 'chat',
      component: ChatView,
      meta: { requiresAuth: true },
    },
    {
      path: '/chat/:userId',
      name: 'chatRoom',
      component: ChatRoomView,
      meta: { requiresAuth: true },
    },
    {
      path: '/mine',
      name: 'mine',
      component: MineView,
      meta: { requiresAuth: true },
    },
    {
      path: '/post/:id',
      name: 'post-detail',
      component: PostDetailView,
      meta: { requiresAuth: true },
    },
    {
      path: '/create-post',
      name: 'post-create',
      component: PostCreateView,
      meta: { requiresAuth: true },
    },
    {
      path: '/user/:id',
      name: 'user-profile',
      component: UserProfileView,
      meta: { requiresAuth: true },
    },
    {
      path: '/face-verify',
      name: 'face-verify',
      component: FaceVerifyView,
      meta: { requiresAuth: true },
    },
    // {
    //   path: '/profile',
    //   name: 'profile',
    //   component: () => import('../views/ProfileView.vue'),
    //   meta: { requiresAuth: true } // 需要登录
    // }
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  if (to.meta.requiresAuth) {
    if (!authStore.isAuthenticated) {
      next({ name: 'auth' })
    } else if (!authStore.faceVerified && to.name !== 'face-verify') {
      next({ name: 'face-verify' })
    } else {
      next()
    }
  } else {
    // 不需要登录的页面，直接放行
    next()
  }
})

export default router
